// 新增学生
$('#addStudentsBtn').click(function() {
    const name = $('#addStudentsName').val();
    const age = $('#addStudentsAge').val();
    const gender = $('[name=addStudentsGender]:checked').val();

    $.ajax({
        url: '/students/createStudents',
        type: 'POST',
        data: {
            name,
            age,
            gender
        },
        success(res) {
            console.log('新增结果', res);
            if (res.code) {
                showStudents();

            }
        }
    })
})

showStudents();

// 学生列表初始化
async function showStudents() {
    const studentsData = await getStudentsData();
    studentsRender(studentsData);
}

// 获取学生数据
function getStudentsData() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/students/getStudents',
            type: 'GET',
            success(res) {
                if (res.code) {
                    resolve(res.result);
                }
            }
        })
    })
}
// 渲染学生数据
function studentsRender(data) {
    const studentsHtml = data.map(item => {
        return `
            <tr>
                <td>${item._id}</td>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.gender}</td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <a href="#">修改</a>
                    <a href="#">删除</a>
                </td>
            </tr>
        `
    }).join('');
    $('#studentsTb').html(studentsHtml);
}